// pages/recharge/recharge.js
const rechargeService = require('../../../../api/rechargeService.js')
const memberService = require('../../../../api/memberService.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    rechargeList: [],
    balance: 0.00,
    serviceTel: '',
    phone: false
  },
  rechargeClick: function (val) {
    var that = this
    var id = val.currentTarget.dataset.id;
    console.log(id)
    //设置当前样式
    that.setData({
      'currentItem': id
    })
  },
  // 检查当前用户是否登录授权
  checkAuth: function () {
    try {
      if (!app.globalData.userInfo) {
        return false;
      } else {
        return true;
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  // 获取充值金额
  getRechargeList: function () {
    rechargeService.query().then(res => {
      console.log(res)
      let tempList = []
      res.forEach(item => {
        let tempItem = {
          amount: item.amount,
          discountAmount: item.discountAmount,
          discountMessage: item.discountMessage ? item.discountMessage : '',
          donationAmount: item.donationAmount,
          rechangeMoneyId: item.rechangeMoneyId,
        }
        tempList.push(tempItem)
      });
      console.log(tempList)
      this.setData({
        rechargeList: tempList
      })
    })
  },
  // 确认充值
  toPayRecharge: function () {
    const that = this
    let rechangeMoneyId = this.data.currentItem
    if (rechangeMoneyId !== '' && rechangeMoneyId !== undefined) {
      console.log(rechangeMoneyId)
      let postData = {
        rechangeMoneyId: rechangeMoneyId,
        sourceType: 'WX_XCX'
      }
      rechargeService.createOrder(postData).then(res => {
        console.log(res)
        let orderId = res.id
        let tempData = {
          orderId: orderId,
          // payMethod: 'SWIFTPASS'
          payMethod: 'WX_MINI_APP'
        }
        rechargeService.getPaySign(tempData).then(res => {
          console.log(res)
          var resData = JSON.parse(res);
          var sign = JSON.parse(resData.sign)
          let packageValue = ''
          if (tempData.payMethod === 'SWIFTPASS') {
            packageValue = sign.package
          } else if (tempData.payMethod === 'WX_MINI_APP') {
            packageValue = sign.packageValue
          }
          wx.requestPayment({
            'timeStamp': sign.timeStamp,
            'nonceStr': sign.nonceStr,
            'package': packageValue,
            'signType': sign.signType,
            'paySign': sign.paySign,
            'success': function (res) {
              wx.showToast({
                title: '充值成功',
                icon: 'none',
                duration: 2000
              })
            },
            'fail': function (res) {
              console.log('支付失败')
              console.log(res)
              if (res.errMsg === 'requestPayment:fail cancel') {
                wx.showToast({
                  title: '您取消了支付~',
                  icon: 'none',
                  duration: 2000
                })
              } else {
                wx.showToast({
                  title: res.errMsg,
                  icon: 'none',
                  duration: 2000
                })
              }
            }
          })
        }).catch(err => {
          wx.showToast({
            title: err.message,
            icon: 'none',
            duration: 2000
          })
        })
      }).catch(e => {
        wx.showToast({
          title: e.message,
          icon: 'none',
          duration: 2000
        })
      })
    } else {
      wx.showToast({
        title: '请选择充值金额~',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 余额明细
  toBalance: function () {
    wx.navigateTo({
      url: '../balance/balance'
    })
  },
  // 重置密码
  toResetPassword: function () {
    wx.navigateTo({
      url: '../resetPassword/resetPassword'
    })
  },
  // 获取余额
  getBalance: function () {
    memberService.getMbrBalance().then(res => {
      this.setData({
        balance: res
      })
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    const that = this
    this.setData({
      serviceTel: app.globalData.servicePhone
    })
    const loginStatus = that.checkAuth()
    if (loginStatus) {
      if (app.globalData.userInfo.member) {
        this.getRechargeList()
        this.getBalance()
      } else {
        wx.showToast({
          title: '您还不是会员，请先绑定手机号码成为会员',
          icon: 'none',
          duration: 2000
        })
        setTimeout(() => {
          that.handlePopupPhone()
        }, 2000);
      }
    } else {
      // try {
      //   wx.showModal({
      //     title: '提示',
      //     content: '请登录后查看',
      //     success: function (res) {
      //       if (res.confirm) {
      //         console.log('用户点击确定')
      //         wx.navigateTo({
      //           url: '../my/my'
      //         })
      //       } else if (res.cancel) {
      //         console.log('用户点击取消')
      //       }
      //     }
      //   })
      // } catch (error) {
      //   wx.showToast({
      //     title: error.message,
      //     icon: 'none',
      //     duration: 2000
      //   })
      // }
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (this.data.phone === true) {
      this.handlePopupPhone()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 用户登录组件事件处理
  handleUserLogin: function () {
    console.log(app.globalData.userInfo)
    const self = this
    if (app.globalData.userInfo) {
      const user = app.globalData.userInfo
      if (app.globalData.userInfo.member) {
        self.getRechargeList()
        self.getBalance()
      } else {
        self.handlePopupPhone()
      }
    }
  },
  handlePopupPhone: function () {
    if (!app.globalData.userInfo.member) {
      this.setData({
        phone: true
      });
    } else {
      this.setData({
        phone: false
      })
      this.getRechargeList()
      this.getBalance()
    }
  },
  handleBindPhone: function (e) {
    console.log(e.detail)
    if (e.detail.bindMobile === true) {
      this.handlePopupPhone()
    }
  }
})